<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>测试主题</title>
    <style>
      :root {
        --body-background: rgb(248, 244, 212);
        --text-color: #000;
      }
      html[data-theme="dark"] {
        --body-background: rgb(58, 70, 90);
        --text-color: #eee;
      }
      body {
        padding-top: 200px;
        height: 100vh;
        width: 100vw;
        margin: 0;
        background: var(--body-background);
        text-align: center;
        color: var(--text-color);
      }
    </style>
  </head>
  <body>
    <div>
      <select>
        <option value="light">白天模式</option>
        <option value="dark">黑夜模式</option>
        <option value="os">跟随系统</option>
      </select>
    </div>
    <h1>测试主题变色</h1>

    <script>
      const select = document.querySelector("select");
      const html = document.querySelector("html");
      // 获取用户设置的主题，默认是跟随系统
      const localTheme = localStorage.getItem("theme") || "os";
      settingTheme(localTheme);
      // 设置select选中的值
      select.value = localTheme;

      select.onchange = (e) => {
        const theme = e.target.value;
        settingTheme(theme);
        localStorage.setItem("theme", theme);
      };

      function settingTheme(theme) {
        // 如果是跟随系统，就获取系统的主题
        if (theme === "os") {
          const osThemeIsDark = matchMedia(
            "(prefers-color-scheme: dark)"
          ).matches;
          html.dataset.theme = osThemeIsDark ? "dark" : "light";
        } else {
          html.dataset.theme = theme;
        }
      }

      matchMedia("(prefers-color-scheme: dark)").addEventListener(
        "change",
        (event) => {
          html.dataset.theme = event.matches ? "dark" : "light";
        }
      );
    </script>
  </body>
</html>
